package com.page.controller;

import com.common.Products;

import org.springframework.cloud.client.ServiceInstance;

import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

/**
 * Author：毕龙
 * Date: 2023/9/2 14:06
 */
@RestController
@RequestMapping("/page")
public class PageController {

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private DiscoveryClient discoveryClient;

    @RequestMapping("/getData")
    public Products getPage(Integer id) {
        //通过RestTemplate发送远程调用
        //基于HTTP访问
        /*Products products = restTemplate.getForObject("http://localhost:9000/product/query/" + id,
                Products.class);*/


        //1、获取Eureka中的实例集合
        List<ServiceInstance> instances = discoveryClient.getInstances("tedu-service-product");
        //2.获取集合中的第一个实例
        ServiceInstance instance = instances.get(0);

        //3.根据实例获取主机获取端口号
        String host = instance.getHost();
        int port = instance.getPort();
        String url = "http://" + host + ":" + port + "/product/query/" + id;
        //4.调用
        Products products = restTemplate.getForObject(url, Products.class);
        return products;
    }

    @RequestMapping("/getPort")
    public String getProductServerPort() {
        String url = "http://tedu-service-product/server/query";
        return restTemplate.getForObject(url, String.class);
    }


}
